package sync

import (
	"fmt"
	syncDto "news_for_deepseek_interface/dto/admin/sync"
	"news_for_deepseek_interface/model"
)

func List(params syncDto.ListRequest) (response syncDto.ListResponse, err error) {

	where := "1=1"
	db := model.GetInstance().GetDB()

	if params.Title != nil {
		where += " AND title LIKE '%" + *params.Title + "%'"
	}

	if params.Desc != nil {
		where += " AND seo_desc LIKE '%" + *params.Desc + "%'"
	}

	if params.Keyword != nil {
		where += " AND seo_keyword LIKE '%" + *params.Keyword + "%'"
	}

	if params.Text != nil {
		where += " AND text LIKE '%" + *params.Text + "%'"
	}

	if params.Content != nil {
		where += " AND content LIKE '%" + *params.Content + "%'"
	}

	if params.SyncAt != nil && len(*params.SyncAt) == 2 {
		where += " AND sync_at BETWEEN '" + (*params.SyncAt)[0] + "' AND '" + (*params.SyncAt)[1] + "'"
	}

	if params.MkId != nil {
		where += " AND mk_id LIKE '%" + *params.MkId + "%'"
	}

	where += " AND sync_status = 1"

	// 获取总数
	var total int64
	if err = db.Model(&model.NewsModel{}).Where(where).Count(&total).Error; err != nil {
		err = fmt.Errorf("数量查询失败%s", err.Error())
		return
	}

	// 分页查询
	offset := (params.Page - 1) * params.Limit
	var data []model.NewsModel
	if err = db.Model(&model.NewsModel{}).Where(where).
		Offset(offset).
		Limit(params.Limit).
		Order("created_at DESC").
		Find(&data).Error; err != nil {
		err = fmt.Errorf("数据查询失败%s", err.Error())
		return
	}

	// 构建响应
	response = syncDto.ListResponse{
		List:  make([]syncDto.Sync, 0),
		Total: total,
		Page:  params.Page,
		Limit: params.Limit,
	}

	for _, v := range data {

		response.List = append(response.List, syncDto.Sync{
			Id:                    v.Id,
			TypeClassifyId:        v.TypeClassifyId,
			TypeClassifyTitle:     model.ClassifyModel{}.GetClassifyTitle(v.TypeClassifyId),
			BusinessClassifyId:    v.BusinessClassifyId,
			BusinessClassifyTitle: model.ClassifyModel{}.GetClassifyTitle(v.BusinessClassifyId),
			Title:                 v.Title,
			SeoDesc:               v.SeoDesc,
			SeoKeyword:            v.SeoKeyword,
			Text:                  v.Text,
			Content:               v.Content,
			CreatedAt:             v.CreatedAt.Format("2006-01-02 15:04"),
			SyncAt:                v.SyncAt.Format("2006-01-02 15:04"),
			MkId:                  v.MkId,
		})
	}

	return
}
